package com.hamaluik.TradeIn;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.util.config.Configuration;
import org.bukkit.util.config.ConfigurationNode;

public class TradeInRecipeHandler {
	private TradeIn plugin;
	private TradeInItemHandler itemHandler;
	public Map<String, TradeInRecipe> recipes = new HashMap<String, TradeInRecipe>();
	
	// grab the main plugin so we can use it later
	public TradeInRecipeHandler(TradeIn instance, TradeInItemHandler _itemHandler) {
		plugin = instance;
		itemHandler = _itemHandler;
	}
	
	public boolean recipeExists(String name) {
		return recipes.containsKey(name);
	}
	
	public void load() {		
		// open and load the config file
		File configFile = new File(plugin.getDataFolder() + "/recipes.yml");
		Configuration config = new Configuration(configFile);
		config.load();
		
		// go through the recipes list
		List<ConfigurationNode> recipesList = config.getNodeList("recipes", null);
		Iterator<ConfigurationNode> it = recipesList.iterator();
		while(it.hasNext()) {
			ConfigurationNode node = it.next();
			TradeInRecipe recipe = new TradeInRecipe();
			recipe.result = node.getString("result");
			recipe.amount = node.getInt("amount", 1);
			recipe.value = node.getString("value", "0");
			
			List<ConfigurationNode> ingredientsList = node.getNodeList("ingredients", null);
			Iterator<ConfigurationNode> i = ingredientsList.iterator();
			while(i.hasNext()) {
				ConfigurationNode ingredient = i.next();
				
				String name = ingredient.getString("name");
				Integer amount = ingredient.getInt("amount", 1);
				String value = ingredient.getString("value", "*");
				
				// create an item stack here
				ItemStack itemStack = new ItemStack(itemHandler.lookupItem(name), amount, (short)itemHandler.lookupValue(value));
				// and add it to the recipe ingredients list!
				recipe.ingredients.add(itemStack);
			}
			
			// and add the recipe to the list...
			recipes.put(recipe.result, recipe);
		}
	}
	
	public Integer maxTrades(String recipeName, Player player) {		
		// and grab the ingredients required..
		TradeInRecipe recipe = recipes.get(recipeName);
		
		Integer amount = 9999;
		
		// now loop through all the ingredients
		// and find the maximum for that ingredient
		// and take the minimum
		for(Iterator<ItemStack> it = recipe.ingredients.iterator(); it.hasNext();) {
			// grab this item stack
			ItemStack stack = it.next();
			
			// count how many the player has..
			Integer count = itemHandler.countItems(player, stack);
			
			// the number of trades that can be done with this ingredient
			Integer number = count / stack.getAmount();
			
			// lower the amount we can trade
			if(amount > number) {
				amount = number;
			}
		}
		
		return amount;
	}
}
